package com.jie.deletefile.Gongju.comment;

import android.app.ActivityManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Debug;

import com.jie.deletefile.Gongju.Entity.AppInfo;
import com.jie.deletefile.Gongju.Entity.RuningAppInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/8/12.
 */
public class AppInfoManager {

    //懒汉式，单例模式
    private static AppInfoManager appInfoManager;
    private PackageManager packageManager;
    private Context context;
    private ActivityManager activityManager;


    private List<AppInfo> allPackageInfos = new ArrayList<>();
    private List<AppInfo> userPackageInfos = new ArrayList<>();
    private List<AppInfo> systemPackageInfos = new ArrayList<>();


    private AppInfoManager(Context context) {
        this.context = context;
        packageManager = context.getPackageManager();
        activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);

    }

    //获取单例对象
    public static AppInfoManager getAppInfoManager(Context context) {
        if (appInfoManager == null) {
            synchronized (context) {
                if (appInfoManager == null) {
                    appInfoManager = new AppInfoManager(context);
                }
            }
        }
        return appInfoManager;
    }

    public static final int RUNING_APP_TYPE_SYS = 0;
    public static final int RUNING_APP_TYPE_USER = 1;

    public Map<Integer, List<RuningAppInfo>> getRuningAppInfos() {
        Map<Integer, List<RuningAppInfo>> data = new HashMap<>();
        List<RuningAppInfo> userdata = new ArrayList<>();
        List<RuningAppInfo> sysdata = new ArrayList<>();
        //通过activityManager获取所有正在运行的应用进程信息，返回集合
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();

        //遍历
        for (ActivityManager.RunningAppProcessInfo appProcessInfo : runningAppProcesses) {
            //该进程的优先级：前台进程，可视进程，服务，后台进程，空进程
            int importance = appProcessInfo.importance;
            //进程名
            String processName = appProcessInfo.processName;
            //端口号
            int pid = appProcessInfo.pid;
            if (importance >= ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE) {
                Drawable drawable;
                String labelName;
                long size;

                Debug.MemoryInfo[] processMemoryInfo = activityManager.getProcessMemoryInfo(new int[]{pid});
                size = processMemoryInfo[0].getTotalPrivateDirty()*1024;

                try {
                    //获取ApplicationInfo对象，作为参数传入getApplicationIcon()方法和getApplicationLabel()
                    ApplicationInfo applicationInfo = packageManager.getApplicationInfo(processName, PackageManager.GET_META_DATA | PackageManager.GET_SHARED_LIBRARY_FILES);
                    //通过packageManager获取应用图标
                    drawable = packageManager.getApplicationIcon(applicationInfo);
                    labelName = packageManager.getApplicationLabel(applicationInfo).toString();

                    //封装为RunningAPPInfo对象
                    RuningAppInfo runningAppInfo = new RuningAppInfo(processName,drawable,labelName,size);

                    //根据flag，添加到对应的集合
                    if((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0){
                        //系统应用将isSystem设置为true,将isClear设置为false;
                        runningAppInfo.setIsclean(false);
                        runningAppInfo.setIssystem(true);
                        //将封装好的RunningAPPInfo添加到集合
                        sysdata.add(runningAppInfo);
                    }else{
                        //用户应用与上面相反
                        runningAppInfo.setIsclean(true);
                        runningAppInfo.setIssystem(false);
                        //将封装好的RunningAPPInfo添加到集合
                        userdata.add(runningAppInfo);
                    }

                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }

        //将两个集合装入map
        data.put(RUNING_APP_TYPE_SYS,sysdata);
        data.put(RUNING_APP_TYPE_USER,userdata);
        return data;
    }


    /**
     * 用来返回所有应用程序列表
     */
    public List<AppInfo> getAllPackageInfo(boolean isReset) {
        if (isReset) {
            loadAllActivityPackager();

        }
        return allPackageInfos;

    }

    /**
     * 用来返回所有系统应用程序列表
     */
    public List<AppInfo> getSystemPackageInfo(boolean isReset) {

        if (isReset) {
            loadAllActivityPackager();
            systemPackageInfos.clear();
            for (AppInfo appInfo : allPackageInfos) {
                if ((appInfo.getPackageInfo().applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
                    systemPackageInfos.add(appInfo);
                } else {

                }
            }
        }

        return systemPackageInfos;

    }

    /**
     * 用来返回所有用户应用程序列表
     */
    public List<AppInfo> getUserPackageInfo(boolean isReset) {
        if (isReset) {
            loadAllActivityPackager();
            systemPackageInfos.clear();
            for (AppInfo appInfo : allPackageInfos) {
                if ((appInfo.getPackageInfo().applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {

                } else {
                    userPackageInfos.add(appInfo);
                }
            }
        }
        return userPackageInfos;
    }


    private void loadAllActivityPackager() {
        List<PackageInfo> infos = packageManager.getInstalledPackages(PackageManager.GET_ACTIVITIES);
        allPackageInfos.clear();
        for (PackageInfo info : infos) {
            allPackageInfos.add(new AppInfo(info));
        }
    }

    public void killALLProcesses(){
        //获取正在运行的所有应用的信息的集合
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        for(ActivityManager.RunningAppProcessInfo appProcessInfo: runningAppProcesses){
            //获取procecssName,这个名字在后面杀死进程的时候要作为参数传入对应的方法
            String processName = appProcessInfo.processName;
            //得到进程的优先级
            int importance = appProcessInfo.importance;

            //根据优先级确定是否杀掉该进程
            if(importance>=ActivityManager.RunningAppProcessInfo.IMPORTANCE_SERVICE){
                try {
                    ApplicationInfo applicationInfo = packageManager.getApplicationInfo(processName, PackageManager.GET_META_DATA | PackageManager.GET_SHARED_LIBRARY_FILES);
                    if((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0){

                    }else{
                        //通过processName杀掉该进程
                        activityManager.killBackgroundProcesses(processName);
                    }

                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    public void killALLProcesses(String processName){
        //根据processName 杀掉该进程
        activityManager.killBackgroundProcesses(processName);

    }





}
